<?php


namespace App\Http\Controllers;

use App\Models\Admin;
use App\Models\Cities;
use App\Models\MakeMaster;
use App\Models\ModelMaster;
use App\Models\ProvinceMaster;
use App\Models\RollMaster;
use App\Models\Warranty;
use App\Models\WarrantyImage;
use App\Models\WarrantyLogs;
use App\Models\WarrantyToVehicleCoverage;
use App\Services\UploadService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class WarrantyController
{
    public function save(Request $request)
    {
        $id = $this->checkHeader($request);

        try {
            $province = $request->input('province') ?? '';
            $city = $request->input('city') ?? '';
            $district = $request->input('district') ?? '';
            $dealer = Admin::withTrashed()->find($id);
            if (empty($dealer) || empty($dealer->id) || empty($dealer->abbr)) {
                return response()->json([
                    'code' => 1000,
                    'msg' => '装贴门店为空或不存在！'
                ]);
            }
            $distributor = $dealer;
            if ($dealer->user_type == 3) {
                $distributor = Admin::withTrashed()->find($dealer->creator_id);
                if (empty($distributor->id) || empty($distributor->abbr)) {
                    return response()->json([
                        'code' => 1000,
                        'msg' => '装贴门店所属不存在！'
                    ]);
                }
            }
            $provinceData = ProvinceMaster::where('simplified_chiness_value', 'like', '%' . str_replace('省', '', mb_substr($province, 0, 2)) . '%')->first();
            if (mb_strpos($city, '省直辖县') !== false) {
                $city = $district;
            }
            $cityData = Cities::where('simplified_chiness_value', 'like', '%' . str_replace('省', '', mb_substr($city, 0, 2)) . '%')
                ->where('province_id', $provinceData->id)
                ->first();

            $warrantyId = $request->input('warranty_id') ?? '';
            if (!empty($warrantyId)) {
                $model = Warranty::where('id', $warrantyId)->first();
                if (!$model) {
                    $model = new Warranty();
                }
                if ($model->approved == 1) {
                    return response()->json([
                        'code' => 1000,
                        'msg' => '该单据已通过，不能修改！'
                    ]);
                }
            } else {
                $model = new Warranty();
            }

            DB::beginTransaction();
            $diff = wDiff1($model);
            $model = wSave($model);
            if (empty($model->warranty_id)) {
                $model->warranty_id = makeWarrantyId($model->installation_date);
            }
            if (empty($model->created_by)) {
                $model->created_by = $id;
            } else {
                $model->updated_by = $id;
            }
            $model->dealer_name = $dealer->abbr;
            $model->distributor_id = $distributor->id;
            $model->distributor_name = $distributor->abbr;
            $model->user_id = $id;
            $model->region_id = 1;
            $model->province_id = $provinceData->id ?? 0;
            $model->city = $cityData->id ?? 0;
            $model->user_id = $id;
            $model->approved = 3;
            $model->save();
            if (empty($model->pre_id)) {
                warrantyPart($model); // 更新安装部位
            }
            rwI1($model); // 更新安装图片
            $res = vWV5($model->id);
            if (!empty($res)) {
                DB::rollback();//数据库回滚
                $error_msg = @$res[0] ?: '数据异常，稍后重试！';
                return response()->json([
                    'code'  => 1000,
                    'msg'   => $error_msg
                ]);
            }
            $coverages = WarrantyToVehicleCoverage::where('warranty_id', $model->id)
                ->get(['roll_number', 'length', 'part_id']);
            foreach ($coverages as $k => $v) {
                $roll = RollMaster::where('roll_number', $v->roll_number)->first();
                if (empty($roll)) {
                    DB::rollback();
                    return response()->json([
                        'code'  => 1000,
                        'msg'   => '卷号不存在，请先保存草稿，稍后重试！'
                    ]);
                }
                $roll->status = 2;
                $roll->save();
//                $e = minusRestlen($model->user_id, $v->roll_number, $v->length);
//                if (empty($e)) {
//                    DB::rollback();
//                    return response()->json([
//                        'code'  => 1000,
//                        'msg'   => '卷号数据异常，请先保存草稿，稍后重试！'
//                    ]);
//                }
            }

            if (!empty($diff)) {
                $wlogs = new WarrantyLogs();
                $wlogs->warranty_id = $model->id;
                $wlogs->status = 9;
                $wlogs->note = json_encode($diff);
                $wlogs->save();
            }
            DB::commit();
        } catch (\Exception $exception){
            DB::rollback();//数据库回滚
            return response()->json([
                'code'  => 1000,
                'msg'   => $exception->getMessage() ?: '服务器异常'
            ]);
        }

        return response()->json([
            'code'  => 0,
            'msg'   => 'success'
        ]);
    }

    public function price(Request $request)
    {
        $id = $this->checkHeader($request);
        $model = DB::table('roll_master')
            ->select('roll_master.id', 'roll_master.roll_number', 'roll_restlen.restlen', 'film_type_master.simplified_chiness_value as film_type_name')
            ->leftJoin('roll_restlen', 'roll_master.roll_number',   'roll_restlen.roll_number')
            ->leftJoin('film_type_master', 'film_type_master.id', 'roll_master.film_type_id');
        if (!empty($request->input('roll_number'))) {
            $model = $model->where('roll_master.roll_number', 'like', '%' . $request->input('roll_number') . '%');
        }
        $data = $model->where('roll_restlen.restlen', '>', 0)
            ->where('roll_restlen.user_id', $id)
            ->get();
        Log::info($data);
        return response()->json([
            'code' => 0,
            'data' => $data
        ]);
    }

    public function uploadFile(Request $request)
    {
        $this->checkHeader($request);
        $file = $request->file('file');
        if (empty($file)) {
            return response()->json([
                'code'  => 1000,
                'msg'   => '缺少文件'
            ]);
        }
        $ext = ["png", "jpg", "jpeg", "gif", "bmp"];
        $extension = $file->getClientOriginalExtension();

        if (!in_array($extension, $ext)) {
            return ['status'=>false, 'msg'=>'图片格式错误！'];
        }
        $fileName = $file->getClientOriginalName();
        $file_name = date('Ym') . '/' . md5($fileName . date('YmdHis') . mt_rand(1111111, 9999999)) . '.' . $extension;
        $imageUrl = (new UploadService())->uploadAliOss(file_get_contents($file->getRealPath()), $file_name);
        if (empty($imageUrl['oss-request-url'])) {
            return ['status'=>false, 'msg'=>'上传失败！'];
        }
        $url = str_replace('https://xpel-dengwho.oss-cn-shanghai.aliyuncs.com', 'https://image-xpel.dengwho.com', $imageUrl['oss-request-url']);
        return [
            'code' => 0,
            'msg'  => 'success',
            'data' => [
                'url'   => $url,
            ]
        ];
    }

    public function carBrand(Request $request)
    {
        $this->checkHeader($request);
        $result = DB::table('make_master')
            ->select('id', 'simplified_chiness_value as brand_name')
            ->whereNull('deleted_at')
            ->where('status', 1)
            ->groupBy('simplified_chiness_value')
            // ->orderByRaw("CONVERT(brand_name USING gbk)")
            ->orderByRaw("CONVERT(brand_name USING gbk) DESC")
            ->get();

        return response()->json([
            'code'  => 0,
            'data'  => $result
        ]);
    }

    public function carModel(Request $request)
    {
        $this->checkHeader($request);

        $make_name = $request->input('brand_name');
        $result = DB::table('model_master')
            ->select('model_master.id', 'model_master.simplified_chiness_value as model_name')
            ->leftJoin('make_master', 'make_master.id', 'model_master.make_id')
            ->where('make_master.simplified_chiness_value', $make_name)
            ->whereNull('make_master.deleted_at')
            ->whereNull('model_master.deleted_at')
            ->groupBy('model_master.simplified_chiness_value')
            ->get();

        return response()->json([
            'code'  => 0,
            'data'  => $result
        ]);
    }

    public function partMasters(Request $request)
    {
        $this->checkHeader($request);
        $parts = DB::table('part_master')->select('id', 'simplified_chiness_value as part_name')
            ->whereNull('deleted_at')
            ->orderBy('order')
            ->get();

        return response()->json([
            'code'  => 0,
            'data'  => $parts
        ]);
    }

    public function constructionType(Request $request) {
        $this->checkHeader($request);
        return response()->json([
            'code'  => 0,
            'data'  => [
                [
                    'id'    => 1,
                    'desc'  => '专车专用'
                ],
                [
                    'id'    => 2,
                    'desc'  => '手工'
                ],
            ]
        ]);
    }

    public function checkHeader(Request $request)
    {
        $token = $request->header('Authorization');
        if (!$token) {
            exit(json_encode([
                'code'  => 1100,
                'msg'   => '登录失效'
            ]));
        }
        return $token;
    }

    public function getWarranty(Request $request)
    {
        $warrantyId = $request->input('warranty_id');
        if(empty($warrantyId)){
            return response()->json([
                'code' => 1000,
                'msg' => '参数异常！'
            ]);
        }
        $warranty = DB::table('warranty')
            ->leftJoin('users', 'users.id', 'warranty.user_id')
            ->leftJoin('make_master', 'make_master.id', 'warranty.make_id')
            ->leftJoin('model_master', 'model_master.id', 'warranty.model_id')
            ->select('warranty.warranty_id',
                'warranty.id',
                'model_master.simplified_chiness_value as model_name',
                'warranty.first_name as car_owner_name',
                'make_master.simplified_chiness_value as maker_name',
                'warranty.year_id as maker_year',
                'users.abbr as store_name',
                'warranty.license_plate',
                'warranty.vin_number',
                'warranty.phone_number',
                'warranty.email_address',
                'warranty.city as city_id',
                'warranty.province_id',
                'warranty.address',
                'warranty.make_id',
                'warranty.model_id',
                'installer_name',
                'installation_date',
                'installation_price',
                'additional_comments')
            ->where('warranty.warranty_id', $request->input('warranty_id'))
            ->first();
        if (empty($warranty)) {
            return response()->json([
                'code'  => 1000,
                'msg'   => '未查询到质保ID'
            ]);
        }
        $coverages = DB::table('warranty_to_vehicle_coverage as wc')
            ->leftJoin('part_master', 'part_master.id', 'wc.part_id')
            ->leftJoin('film_type_master',  'film_type_master.id', 'wc.film_type_id')
            ->select('wc.roll_number', 'wc.length', 'wc.precut_or_manual','part_master.simplified_chiness_value as part_name', 'film_type_master.simplified_chiness_value as film_name')
            ->where('warranty_id', $warranty->id)->get();
        if (empty($coverages)) {
            $warranty->coverages = [];
            return response()->json([
                'code' => 0,
                'msg'   => 'success',
                'data'  => $warranty
            ]);
        }

        $warranty->installation_date = $warranty->installation_date ? date('Y-m-d', strtotime($warranty->installation_date)) : '';
        $warranty->coverages = $coverages;
        $images = WarrantyImage::where('warranty_id', $warranty->id)->pluck('image_src');
        $warranty->images = $images;

        $provinceData = ProvinceMaster::where('id',$warranty->province_id)->first();
        $warranty->province = $provinceData->simplified_chiness_value ?? "";

        $cityData = Cities::where('id',$warranty->city_id)
            ->where('province_id', $warranty->province_id)
            ->first();
        $warranty->city = $cityData->simplified_chiness_value ?? "";
        return response()->json([
            'code'  => 0,
            'msg'   => 'success',
            'data'  => $warranty
        ]);
    }

    public function warrantyList(Request $request)
    {
        $id = $this->checkHeader($request);
        $keywords = $request->input('keywords');
        if (empty($keywords) && empty($id)) {
            return [
                'code'  => 0,
                'data'  => []
            ];
        }
        $status = $request->input('status') ?: 1;
        $pageSize = $request->input('page_size') ?: 10;
        $page = $request->input('page');
        $db = DB::table('warranty')
            ->leftJoin('model_master', 'model_master.id', 'warranty.model_id')
            ->leftJoin('make_master', 'make_master.id', 'warranty.make_id')
            ->leftJoin('warranty_to_vehicle_coverage as wc', 'wc.warranty_id', 'warranty.id')
            ->leftJoin('part_master', 'part_master.id', 'wc.part_id')
            ->leftJoin('film_type_master', 'film_type_master.id', 'wc.film_type_id')
            ->select('warranty.warranty_id', 'warranty.id',
                'warranty.license_plate', 'warranty.vin_number', 'model_master.simplified_chiness_value as car_model', 'make_master.simplified_chiness_value as maker_model',
                'warranty.first_name as car_owner_name', 'warranty.additional_comments',
                'installer_name', 'warranty.created_at as installation_date', 'additional_comments', 'film_type_master.simplified_chiness_value as film_name')
            ->whereIn('wc.film_type_id', [130,133])
            ->where('warranty.user_id', $id)
            ->where('warranty.approved', $status);
        if (!empty($request->input('keywords'))) {
            $keywords = $request->input('keywords');
            $db = $db->where(function ($query) use ($keywords) {
                $query->where('warranty.warranty_id', $keywords)
                    ->orWhere('warranty.phone_number', $keywords)
                    ->orWhere('warranty.license_plate', $keywords)
                    ->orWhere('warranty.vin_number', $keywords)
                    ->orWhere('warranty.first_name', $keywords);
            });
        }
        $list = $db->whereNull('warranty.deleted_at')->offset(($page - 1) * $pageSize)
            ->limit($pageSize)
            ->get()
            ->toArray();

        if (empty($list)) {
            return [
                'code'  => 0,
                'data'  => []
            ];
        }

        return response()->json([
            'code'  => 0,
            'msg'   => 'success',
            'data'  => $list
        ]);
    }
}